<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="height=device-height, initial-scale=1.0" />
    <title>Document</title>
    <style>
      p {
        border: solid;
        padding: 20px;
      }
    </style>
  </head>
  <body>
    <p>
      <img data-src="./imgs/1.jpg" src="./imgs/loading.gif" height="400px" />
    </p>
    <p>
      <img data-src="./imgs/2.jpg" src="./imgs/loading.gif" height="400px" />
    </p>
    <p>
      <img data-src="./imgs/3.jpg" src="./imgs/loading.gif" height="400px" />
    </p>
    <p>
      <img data-src="./imgs/4.jpg" src="./imgs/loading.gif" height="400px" />
    </p>
    <p>
      <img data-src="./imgs/5.jpg" src="./imgs/loading.gif" height="400px" />
    </p>
    <p>
      <img data-src="./imgs/6.jpg" src="./imgs/loading.gif" height="400px" />
    </p>
    <p>
      <img data-src="./imgs/7.jpg" src="./imgs/loading.gif" height="400px" />
    </p>

    <script>
      function loadImg() {
        // 图片的懒加载，只加载看到的图片
        document.querySelectorAll("img[data-src]").forEach((img) => {
          // 判断图片是不是在可视区域
          const gbc = img.getBoundingClientRect();
          if (gbc.top - window.innerHeight < -img.clientHeight) {
            // 使用真正的图片地址，替换loading图片
            img.src = img.dataset.src;
            img.removeAttribute("data-src");
          }
        });
      }

      loadImg();
      window.onscroll = function () {
        loadImg();
      };
    </script>
  </body>
</html>
